
define(['ionic', 'controllers'], function () {
    angular.module('U9Mobile.controllers')
        .controller('DownloadCtrl', ['$scope', 'AppManager', 'UtilService', function ($scope, AppManager, UtilService) {
            $scope.data = {
                search: '',
                unInstallApps: [],
                installApps: []
            };

            $scope.installApp = function (appId) {
                UtilService.showLoading();
                AppManager.installApp(appId).then(function () {
                    UtilService.tipsBottom('下载成功！');
                    refreshAppList();
                }, function () {
                    UtilService.tipsBottom('下载失败！');
                })['finally'](function () {
                    UtilService.hideLoading();
                });
            };
            $scope.unInstallApp = function (appId) {
                UtilService.confirm('确定要删除吗！').then(function (res) {
                    if (res) {
                        UtilService.showLoading();
                        AppManager.unInstallApp(appId).then(function () {
                            UtilService.tipsBottom('删除成功！');
                            refreshAppList();
                        }, function () {
                            UtilService.tipsBottom('删除失败！');
                        })['finally'](function () {
                            UtilService.hideLoading();
                        });
                    }
                });
            };
            $scope.updateApp = function (appId) {
                UtilService.showLoading();
                AppManager.updateApp(appId).then(function () {
                    UtilService.tipsBottom('更新成功！');
                    refreshAppList();
                }, function () {
                    UtilService.tipsBottom('更新失败！');
                })['finally'](function () {
                    UtilService.hideLoading();
                });
            };

            $scope.$on('$ionicView.beforeEnter', function () {
                AppManager.loadingAppPromise.then(function () {
                    refreshAppList();
                });
            });

            function refreshAppList () {
                var installApps = AppManager.getInstallApps();
                AppManager.getAllApps().then(function (allApps) {
                    $scope.data.unInstallApps = AppManager.getUnInstallApps(allApps);
                    $scope.appData.updateAvailable = AppManager.checkUpdateAvailable(installApps, allApps);
                    $scope.data.installApps = installApps;
                }, function () {
                    $scope.data.unInstallApps = [];
                    $scope.data.installApps = installApps;
                });
            }
        }]);
});